package cn.wolfcode.trip.app.filter;

import cn.wolfcode.trip.app.util.UploadUtil;
import org.apache.commons.io.FileUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * Created by 13925 on 2018/10/30.
 */

/**
 * 图片过滤器
 */
public class ImageFilter implements Filter {


    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //转换成Http请求
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String imageUrl = req.getRequestURI();
        File file = new File(UploadUtil.BASE_IMAGE_PATH, imageUrl);
        if (file.exists()) {
            //从共享图片服务中读取图片
            byte[] bytes = FileUtils.readFileToByteArray(file);
            //输出去浏览器,做本次请求相应结果.
            ServletOutputStream out = servletResponse.getOutputStream();
            out.write(bytes);
        } else {
            //图片不存在 ,放行 进入app/admin中查找
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    public void destroy() {

    }
}
